#include "HandleResultModel.hpp"
#include <chrono>
#include <cstring>

using namespace std::chrono_literals;

HandleResultModel::HandleResultModel()
  : resultMemory("/HBTY_HANDLE_SHAREDMEM",1920*1080*3)
  // , sem("/HBTY_HANDLE_SEMAPHORE")
  , threadID(pthread_self())
{
}

HandleResultModel::~HandleResultModel()
{
  if(pthread_equal(pthread_self(),threadID)==0)
    pthread_cancel(threadID);
  if(workThread.joinable())
    workThread.join();
}

void HandleResultModel::Boot(std::function<void(const ImageType& image)> func)
{
  funcResultCallback=func;
  workThread=std::jthread([this](std::stop_token token){
    threadID=pthread_self();
    ImageType newImg;
    newImg.width=1920;
    newImg.height=1080;
    newImg.data_size=1920*1080*3;
    newImg.uuid[0]='0';
    newImg.uuid[1]='\0';
    while(!token.stop_requested())
    {
      std::this_thread::sleep_for(50ms);
      newImg.data=new unsigned char[1920*1080*3];
      // sem.Lock();
      memcpy(newImg.data,resultMemory.GetMemory(),1920*1080*3);
      // sem.Unlock();
      funcResultCallback(newImg);
    }
  });
}
